
import ad from '@service.ad'

let advBanners = []; // 横幅广告存储
let lastAdIndex = -1; // 记录上一次展示的广告索引
let hasShownAd = false; // 标记当前滚动周期内是否已展示广告 
const triggerDistance = 200; // 触发广告展示的滚动距离


let advVideos = [];
let lastAdVIndex = -1;
let hasShownAdV = false;




function handlerAdv(data) {
    const { banners, videos } = data;
    console.log("banners", banners)
    console.log("videos", videos)

    advBanners = banners
    advVideos = videos

    showAd(advBanners[0])
    // showAdV(advVideos[0])

}


function showAdV(item) {
    // console.clear()
    console.log("video adv 2", item)

    const rewardedVideoAd = ad.createRewardedVideoAd({
        adUnitId: item.s1,
    })
    rewardedVideoAd.load().then((e) => {
        console.log("视频广告加载成功");
        rewardedVideoAd.show();
    }).catch((e) => {
        console.log("视频广告加载catch", e)
    })

    rewardedVideoAd.onClose(() => {
        console.log("视频广告关闭");
    })

    rewardedVideoAd.onError((e) => {
        console.log("视频广告加载失败", e)
    })

}

function showAd(item) {
    // console.clear()
    console.log("banner 2", item)
    const id = item.s1;
    const bannerAd = ad.createBannerAd({
        adUnitId: id,
        // style:{
        //     left:0,
        //     top: 26,
        //     width:1080
        // }
    })

    bannerAd.show()
    bannerAd.onLoad((e) => {
        console.log("横幅加载")
    });

    bannerAd.onError((e) => {
        console.log("横幅加载失败", e)
    })

}


function onBannerScroll(y) {
    if (y > triggerDistance && !hasShownAd && advBanners.length > 0) {
        let nextIndex;
        if (advBanners.length === 1) {
            nextIndex = 0;
        } else {
            nextIndex = lastAdIndex === -1 ? 0 : (lastAdIndex + 1) % advBanners.length;
        }
        console.log(123)
        showAd(advBanners[nextIndex]);

        lastAdIndex = nextIndex;
        hasShownAd = true;
    }

    if (y <= 20) {
        hasShownAd = false;
    }
}
function onVideoScroll(y) {
    if (y > triggerDistance && !hasShownAdV && advVideos.length > 0) {
        let nextIndex;
        if (advVideos.length === 1) {
            nextIndex = 0;
        } else {
            nextIndex = lastAdVIndex === -1 ? 0 : (lastAdVIndex + 1) % advVideos.length;
        }
        showAdV(advVideos[nextIndex]);

        lastAdVIndex = nextIndex;
        hasShownAdV = true;
    }

    if (y <= 20) {
        hasShownAdV = false;
    }
}


function onPageScrollFunc(y) {
    onBannerScroll(y)
    onVideoScroll(y)

}







export { handlerAdv, onPageScrollFunc, showAd }